package pub.xspace.nova.system.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import jakarta.servlet.http.HttpServletResponse;
import pub.xspace.nova.common.controller.BaseController;
import pub.xspace.nova.common.domain.AjaxResult;
import pub.xspace.nova.common.exception.CommonException;

/**
 * 文件处理接口
 */
@RestController
@RequestMapping("/files")
public class FileController extends BaseController {
	
	private static final String filePath = System.getProperty("user.dir")+"/files/";//获取当前项目的根路径在加上文件保存路径

	/**
	 * 文件上传接口
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public AjaxResult upload(MultipartFile file) {//文件流的形式接受前端发送过来的文件
		String originalFileName = file.getOriginalFilename();
		if(FileUtil.isDirectory(filePath)) {
			FileUtil.mkdir(filePath);//不存在目录时创建目录
		}
		String fileName = System.currentTimeMillis()+"_"+originalFileName; 
		String realPath = filePath + fileName;
		try {
			FileUtil.writeBytes(file.getBytes(), realPath);
		} catch (IORuntimeException e) {
			e.printStackTrace();
			throw new CommonException(500, "文件上传失败");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CommonException(500, "文件上传失败");
		}
		//返回一个网络连接
		String url = "http://localhost:8088/files/download/"+fileName;
		return success("上传成功",url);
	}
	
	/**
	 * 文件下载
	 * @param fileName
	 * @param response
	 */
	@GetMapping("/download/{fileName}")
	public void download(@PathVariable String fileName,HttpServletResponse response) {
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName,StandardCharsets.UTF_8));
			response.setContentType("application/octet-stream");
			OutputStream os = response.getOutputStream();
			String realPath  = filePath + fileName;
			byte[] bytes = FileUtil.readBytes(realPath);
			os.write(bytes);
			os.flush();
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CommonException(500, "文件下载失败");
		}
	}
	
	@PostMapping("/wang/upload")
	public Map<String,Object> wangEditorUpload(MultipartFile file){
		String originalFilename = file.getOriginalFilename();
		if(!FileUtil.isDirectory(filePath)) {
			FileUtil.mkdir(filePath);
		}
		String fileName = System.currentTimeMillis()+"_"+originalFilename;
		String realPath = filePath + fileName;
		try {
			FileUtil.writeBytes(file.getBytes(), realPath);
		}catch(IOException e) {
			e.printStackTrace();
			throw new CommonException(500,"文件上传失败");
		}
		String url = "http://localhost:8088/files/download/"+fileName;
		//wangEditor 上传图片成功后，需要返回参数
		Map<String,Object> resMap = new HashMap<>();
		List<Map<String,Object>> list = new ArrayList<>();
		Map<String ,Object> urlMap = new HashMap<>();
		urlMap.put("url", url);
		list.add(urlMap);
		resMap.put("errno", 0);
		resMap.put("data", list);
		return resMap;
	}
}
